<template>
  <div id="article-view">
    <div>
      <p>题目：{{ title }}</p>
    </div>内容：
    <div v-html="content"></div>
    <div>情绪：{{emotion}}</div>
    <div>可信度：{{probability}}</div>
    <Button type="error" size="large" @click="del">删除</Button>
  </div>
</template>

<script>
export default {
  name: "article-view",
  data() {
    return {
      title: "",
      content: "",
      id: this.$route.params.id,
      emotion: "",
      probability: 0.0,
    };
  },
  created: function () {
    this.getArticle();
  },
  watch: {
    $route(to, from) {
      this.id = to.params.id;
      this.getArticle();
    },
  },
  methods: {
    getArticle() {
      this.$api.get("articles/", { id: this.id }, (response) => {
        if (response.status == 200) {
          var data = response.data;
          if (data.err_code == 0) {
            data = data.data;
            this.title = data.title;
            this.content = data.content;
            this.getEmotion(data.emotion);
          } else {
            this.$Message.error("请求失败" + data.error);
          }
        }
      });
    },

    getEmotion(emotion_id) {
      if (!emotion_id && typeof emotion_id != "undefined" && emotion_id != 0) {
        this.emotion = "无法分析";
        this.probability = "无法分析";
        return 0;
      }
      this.$api.get("emotion/", { id: emotion_id }, (response) => {
        if (response.status == 200) {
          var data = response.data;
          if (data.err_code == 0) {
            data = data.data;
            var emotion_Chinese = {
              angry: "愤怒",
              happy: "开心",
              sad: "失落",
              tired: "讨厌",
            };
            this.emotion = emotion_Chinese[data.emotion];
            this.probability = data.probability.toFixed(2);
          } else {
            this.$Message.error("请求失败" + data.error);
          }
        }
      });
    },
    del() {
      this.$api.delete("articles/", { id: this.id }, (response) => {
        if (response.status == 200) {
          var data = response.data;
          if (data.err_code == 0) {
            data = data.data;
            if (data.result == true) {
              this.$Message.success("删除成功");
              if (window.history.length <= 1) {
                this.$router.push({ path: "/" });
                return false;
              } else {
                this.$router.go(-1);
              }
            } else {
              this.$Message.error("删除失败");
            }
          } else {
            this.$Message.error("请求失败" + data.error);
          }
        }
      });
    },
  },
};
</script>